package com.tc.itfarm.service.impl;

import com.google.common.collect.Lists;
import com.tc.itfarm.api.model.Page;
import com.tc.itfarm.api.model.PageList;
import com.tc.itfarm.api.model.SingleTableDao;
import com.tc.itfarm.api.util.DateUtils;
import com.tc.itfarm.api.util.EncoderUtil;
import com.tc.itfarm.api.util.PageQueryHelper;
import com.tc.itfarm.dao.RoleDao;
import com.tc.itfarm.model.Role;
import com.tc.itfarm.model.RoleCriteria;
import com.tc.itfarm.model.UserRole;
import com.tc.itfarm.model.ext.Tree;
import com.tc.itfarm.service.RoleService;
import com.tc.itfarm.service.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

	@Resource
	private RoleDao roleDao;
	@Resource
	private UserRoleService userRoleService;

	@Override
	public Integer save(Role role) {
		role.setModifyTime(DateUtils.now());
		if (role.getRecordId() == null) {
			role.setCreateTime(DateUtils.now());
			return this.insert(role);
		}
		return this.update(role);
	}

	@Override
	public List<Role> selectByUserId(Integer userId) {
		List<UserRole> userRoles = userRoleService.selectByUserId(userId);
		if (userRoles.size() < 1) {
			return Lists.newArrayList();
		}
		List<Integer> roleIds = Lists.newArrayList();
		for (UserRole ur : userRoles) {
			roleIds.add(ur.getRoleId());
		}
		RoleCriteria criteria = new RoleCriteria();
		criteria.or().andRecordIdIn(roleIds);
		return roleDao.selectByCriteria(criteria);
	}

	@Override
	public PageList<Role> selectByPageList(String name, Date startDate, Date endDate, Page page) {
		RoleCriteria criteria = new RoleCriteria();
		RoleCriteria.Criteria innerCriteria = criteria.createCriteria();
		if (StringUtils.isNotBlank(name)) {
			innerCriteria.andNameLike(EncoderUtil.toLikeQueryStr(name));
		}
		if (startDate != null) {
			innerCriteria.andCreateTimeGreaterThanOrEqualTo(startDate);
		}
		if (endDate != null) {
			innerCriteria.andCreateTimeLessThanOrEqualTo(endDate);
		}
		return PageQueryHelper.queryPage(page, criteria, roleDao, null);
	}

	@Override
	public List<Tree> selectTree() {
		List<Tree> tree = Lists.newArrayList();
		List<Role> roles = this.selectAll();
		for (Role r : roles) {
			Tree t = new Tree();
			t.setId(r.getRecordId());
			t.setText(r.getName());
			tree.add(t);
		}
		return tree;
	}

	@Override
	protected SingleTableDao getSingleDao() {
		return roleDao;
	}
}
